"""
本地涩图插件
"""
import nonebot
from nonebot import get_driver, get_bot, on_command, on_notice
from nonebot.plugin import on_regex
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.matcher import Matcher
from nonebot.adapters.cqhttp.message import Message, MessageSegment
from .data_source import *
from .tool import CD
# 用于定时任务
from nonebot import require

theCD = CD()

driver = get_driver()
global_config = get_driver().config  # 载入全局设置
g = global_config.dict()
adminID = g["admin_id"]
groupID = g["group_id"]

# notice = on_notice("来点涩图", priority=10, block=True)
reaction = on_regex(r"[来|搞|弄|來|赖|l][张|点|丶|垫|點|电|d][色|瑟|澀|涩|美|s|m][图|圗|圖|t]", priority=50)
update = on_regex(r"小美-更新图库")
switch_off = on_regex(r"小美-私聊关闭", priority=60)
switch_on = on_regex(r"小美-私聊开启", priority=60)
ls_pict = on_regex(r"小美-查看图库", priority=90)
scheduler = require("nonebot_plugin_apscheduler").scheduler


@driver.on_startup
def init():
    print("正在进行debug_test")
    yaml_init()
    pass


switch_key = False


# @scheduler.scheduled_job("interval", seconds=5, id="task0", name="test")
# async def _():
#    print("定时函数运行中")
#    await get_bot().call_api("send_private_msg",
#                       user_id=adminID,
#                       message=Message("测试"),
#                       auto_escape=False)


# 定时开启发送私聊涩图功能（用装饰器设定的任务在运行过程中无法更改）
# "cron" 每日定时工具
@scheduler.scheduled_job("cron", hour=20, minute=30, id="task1", name="schedul_sexypict_open")
async def _():
    global switch_key
    switch_key = True
    await get_bot().call_api("send_group_msg",
                             group_id=groupID,
                             message=Message("==   < 定时任务 >   ==\n--开启私聊特殊功能--"),
                             auto_escape=False)


@scheduler.scheduled_job("cron", hour=2, id="task2", name="schedul_sexypict_close")
async def _():
    global switch_key
    switch_key = False
    await get_bot().call_api("send_group_msg",
                             group_id=groupID,
                             message=Message("==   < 定时任务 >   ==\n--关闭私聊特殊功能--"),
                             auto_escape=False)


@switch_off.handle()
async def _(bot: Bot, event: Event):
    # switch_off.send(Message(event.get_user_id().__str__()))
    if event.get_user_id().__str__() == str(adminID):
        global switch_key
        switch_key = False
        await switch_off.send("--关闭私聊特殊功能--")
    else:
        await switch_off.send("铁憨憨")


@switch_on.handle()
async def _(bot: Bot, event: Event):
    # await switch_on.send(Message(event.get_user_id().__str__()))
    if event.get_user_id().__str__() == str(adminID):
        global switch_key
        switch_key = True
        await switch_on.send("--开启私聊特殊功能--")
    else:
        await switch_on.send("铁憨憨")


@ls_pict.handle()
async def _(bot: Bot, event: Event):
    # 显示图库信息
    str_info = info_image_list()

    await ls_pict.send(Message(str_info))


# 进行发送图片功能的实现测试
@driver.on_bot_connect
async def test(bot: Bot):
    await send_image_test(bot, istest=True)


@update.handle()
async def _(bot: Bot, event: Event):
    yaml_update()
    await update.send("--更新完毕--")


# 根据匹配到的信息发送图片
@reaction.handle()
async def _(bot: Bot, event: Event):
    if theCD.check_cd(event.get_user_id()) == -1:
        # 时间间隔太短，发送道德经
        text = theCD.get_text()
        await reaction.send(text)
        return
    await send_image_test(bot, event, istest=False)


async def send_image_test(bot: Bot, event: Event = None, methon: str = "random", istest: bool = False):
    """
    根据不同的需求发送图片,istest仅对admin账号有效
    :param bot:
    :param event: 消息类型
    :param methon: 发送方式，默认采用random随机

    :return:
    """
    result = await bot.call_api("can_send_image")
    if result["yes"]:
        nonebot.logger.info("可以发送图片")
    else:
        nonebot.logger.error("出错，无法发送图片")
        return
    if istest:
        # Debug 功能代码
        # _message = Message()
        _message = []
        if result["yes"]:
            _message.append(MessageSegment.text("可以发送图片\n"))
        else:
            _message.append(MessageSegment.text("出错，无法发送图片\n"))
        _message.append(MessageSegment.text("测试涩图功能\n"))

        # 查看消息类型
        if event is not None:
            try:
                if event.message_type == "private":
                    _message.append(MessageSegment.text("这是私聊信息\n"))
                    await bot.call_api("send_private_msg",
                                       user_id=adminID,
                                       message=Message(_message),
                                       auto_escape=False)
                if event.message_type == "group":
                    _message.append(MessageSegment.text("这是群聊信息\n"))
                    await bot.send(event, _message)
            except:
                pass

    else:  # 随机获取一张图片，并返回该图片所在文件夹的名称
        try:
            if event.message_type == "private":
                global switch_key
                # 根据管理员设定决定是否发送特制版功能
                if switch_key == True:
                    path_image = get_image("special")
                else:
                    path_image = get_image("common")
                message_image = MessageSegment.image(path_image)
                await bot.send(event, message_image)
            if event.message_type == "group":
                path_image = get_image("common")
                message_image = MessageSegment.image(path_image)
                await bot.send(event, message_image)

        except Exception as e:
            print(repr(e))
